(function (window, $, undefined) {
  'use strict';

  var $tableUser = $('#table-user');

  var dictData = {
    gender: {
      '1': '男',
      '2': '女'
    }
  };

  var tableData = {};
  var cityData = {};
  var roleData = {};

  main(function () {

    util.jqGrid($tableUser, {
      url: ajaxURL.SYSTEM + '/sys/user/getSysUserPageList',
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 320,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { label: '编号', name: 'kid', key: true, width: 50, hidden: true },
        { label: '账号', name: 'account', width: 100 },
        { label: '姓名', name: 'name', width: 100 },
        { label: '性别', name: 'gender', width: 50, formatter: function (v) {
          return dictData.gender[v] || '';
        } },
        { label: '电话', name: 'phone', width: 80 },
        { label: '职权', name: '_role', width: 200, formatter: function (v, o, r) {
          var ret = [];

          $.each(r.roleList, function (_, item) {
            ret.push(item.name);
          });

          return ret.join('、');
        } },
        { label: '管辖城市', name: '_city', width: 200, formatter: function (v, o, r) {
          var ret = [];

          if (r.cityList && r.cityList[0] && +r.cityList[0].cityCode === 0) {
            return '全部';
          }

          $.each(r.cityList, function (_, item) {
            if (cityData[item.cityCode] && cityData[item.cityCode].name) {
              ret.push(cityData[item.cityCode].name);
            }
          });

          return ret.join('、');
        } }
      ],
      pager: '#pager-user',
      loadComplete: function (res) {
        tableData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            tableData[item.kid] = item;
          });
        }
      }
    });

    util.selectHtml($('select[name="gender"]'), dictData.gender, '', '', '请选择');

    // 搜索表格
    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tableUser, data);
    }

    $('#btn-search').click(searchTable);

    var $cityList = $('.city-list');

    getCityList();
    function getCityList() {
      util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
        cityData = {};
        var ret = '';
        $.each(res.data, function (_, item) {
          cityData[item.cityId] = item;
          ret += '<label class="marginR10">';
          ret += '<input type="checkbox" name="cityId" value="' + item.cityId + '">';
          ret += item.name;
          ret += '</label>';
        });

        $cityList.html(ret);

        getRoleList();
      });
    }

    var $roleList = $('.role-list');
    function getRoleList() {
      util.get(ajaxURL.SYSTEM + '/sys/v1/role/getList', function (res) {
        roleData = {};
        var ret = '';
        $.each(res.data, function (_, item) {
          roleData[item.kid] = item;
          ret += '<label class="marginR10">';
          ret += '<input type="checkbox" name="roleId" value="' + item.kid + '">';
          ret += item.name;
          ret += '</label>';
        });

        $roleList.html(ret);

        searchTable();
      });
    }

    var $layerUser = $('#layer-user');
    var $formUser = $('#form-user');

    $.validator.addMethod('isUserString', function (value, element) {
      var isValid = /^[a-zA-Z0-9_@#$%^&*!~]+$/.test(value);
      return this.optional(element) || isValid;
    }, '请填写正确值，仅支持字母、数字和部分特殊字符');

    var $validateUser = $formUser.validate({
      rules: {
        account: { required: true, isUserString: true, maxlength: 30 },
        name: { required: true, maxlength: 20 },
        phone: { required: true },
        gender: { required: true },
        password: { isPassword: true, maxlength: 20 }
      },
      messages: {
        account: { required: '请输入账户', maxlength: '账户名最大长度 30' },
        name: { required: '请输入用户姓名', maxlength: '用户名最大长度 20' },
        phone: { required: '请输入联系电话' },
        gender: { required: '请选择性别' },
        password: { maxlength: '密码最大长度 20' }
      },
      errorPlacement: function (error, element) {    //错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); //这里的element是录入数据的对象
      }
    });

    // 保存用户信息（添加和修改统一入口）
    function saveUser(kid) {
      var data = util.formData($formUser);
      data.kid = kid || '';

      if (kid) {
        if (data.password) {
          data.password = util.sha666(data.password);
        } else {
          delete data.password;
        }
        data.userId = kid;
      } else {
        data.password = util.sha666(data.password || '123456@Kgcx');
      }

      // 获取当前选择的角色列表
      data.roleIds = (function () {
        var ret = [];
        $.each($layerUser.find('.role-list').find('[name]'), function (_, item) {
          var $this = $(this);
          if ($this.prop('checked')) {
            ret.push($this.val());
          }
        });
        return ret.join() || 0;
      })();
      // 获取当前选择的城市列表
      data.cityCodes = (function () {
        var ret = [];
        $.each($layerUser.find('.city-list').find('[name]'), function (_, item) {
          var $this = $(this);
          if ($this.prop('checked')) {
            ret.push($this.val());
          }
        });
        return ret.join() || 0;
      })();

      util.post(ajaxURL.SYSTEM + '/sys/user/' + (kid ? 'updateUserByUserId' : 'addSysUser') + '?' + $.param(data), function (res) {
        console.log(res);
        layer.closeAll();
        util.tip.success(kid ? '修改成功' : '添加成功');
        $tableUser.trigger('reloadGrid');
      });
    }

    $('#btn-add').click(function () {
      util.resetForm($formUser);
      $formUser.find('[name="account"]').removeAttr('disabled');

      // 重置相关数据
      $layerUser.find('.city-list, .role-list').find('[name]').prop('checked', false);

      util.layerOpen2({
        title: false,
        content: $layerUser,
        area: ['800px', ''],
        btn: ['添加', '取消'],
        yes: function (index) {
          if ($validateUser.form()) {
            saveUser();
          }
        }
      });
    });

    // 修改用户
    $('#btn-edit').click(util.oneCheck($tableUser, function (id, data) {
      util.resetForm($formUser);
      $formUser.find('[name="account"]').attr('disabled', 'disabled');

      // 重置相关数据
      $layerUser.find('.city-list, .role-list').find('[name]').prop('checked', false);

      var curData = tableData[id];

      util.fillForm($formUser, curData);

      // 修改时将已选城市进行勾选操作
      var curCityList = (function () {
        var ret = [];
        $.each(curData.cityList, function (_, item) {
          ret.push(item.cityCode);
        });
        return ret;
      })();;
      $layerUser.find('.city-list').find('[name]').each(function () {
        var $this = $(this);
        $this.prop('checked', curCityList.indexOf($this.attr('value')) > -1);
      });
      var curRoleList = (function () {
        var ret = [];
        $.each(curData.roleList, function (_, item) {
          ret.push(item.kid);
        });
        return ret;
      })();
      $layerUser.find('.role-list').find('[name]').each(function () {
        var $this = $(this);
        $this.prop('checked', curRoleList.indexOf(+$this.attr('value')) > -1);
      });

      util.layerOpen2({
        title: false,
        content: $layerUser,
        area: ['800px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          if ($validateUser.form()) {
            saveUser(id);
          }
        }
      });

    }));

    // 删除用户
    $('#btn-del').click(util.oneCheck($tableUser, function (id, data) {
      if (data.account === 'admin') {
        return util.tip.warn('禁止删除该账号');
      }
      layer.confirm('确定删除该用户？', function () {
        util.post(ajaxURL.SYSTEM + '/sys/user/deleteUserByUserId?userId=' + id, function (res) {
          util.tip.success('删除成功');
          $tableUser.trigger('reloadGrid');
        });
      });
    }));

  });


})(window, jQuery);
